'use client';

import { useParams } from 'next/navigation';
import { products } from '@/lib/mockData';
import { useApp } from '@/contexts/AppContext';
import { useToast } from '@/components/Toast';
import { useState } from 'react';

export default function ProductPage() {
  const params = useParams();
  const productId = params.id as string;
  const { dispatch } = useApp();
  const { showToast, ToastContainer } = useToast();
  const [quantity, setQuantity] = useState(1);
  const [isAdding, setIsAdding] = useState(false);

  const product = products.find(p => p.id === productId);

  if (!product) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="text-8xl mb-6">❓</div>
          <h2 className="text-2xl font-bold text-gray-800 mb-4">商品不存在</h2>
          <p className="text-gray-600 mb-8">您访问的商品可能已下架或不存在</p>
          <a
            href="/shop"
            className="bg-gradient-to-r from-yellow-400 to-orange-400 text-black font-bold py-3 px-8 rounded-lg hover:shadow-lg transition-shadow"
          >
            返回商城
          </a>
        </div>
      </div>
    );
  }

  const handleAddToCart = async () => {
    setIsAdding(true);
    
    // 添加多个数量到购物车
    for (let i = 0; i < quantity; i++) {
      dispatch({ type: 'ADD_TO_CART', payload: product });
    }
    
    setTimeout(() => {
      setIsAdding(false);
      showToast(`已添加 ${quantity} 个 ${product.name} 到购物车！`, 'success');
    }, 500);
  };

  const handleBuyNow = () => {
    handleAddToCart();
    setTimeout(() => {
      window.location.href = `/checkout?product=${product.id}&quantity=${quantity}`;
    }, 1000);
  };

  const relatedProducts = products.filter(p => p.id !== productId && p.category === product.category).slice(0, 4);

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-6xl mx-auto px-4">
        {/* 返回链接 */}
        <div className="mb-6">
          <a href="/shop" className="text-blue-600 hover:text-blue-700 flex items-center space-x-2">
            <span>←</span>
            <span>返回商城</span>
          </a>
        </div>

        <div className="grid lg:grid-cols-2 gap-12">
          {/* 商品图片 */}
          <div className="space-y-4">
            <div className={`h-96 bg-gradient-to-br ${product.bgColor} rounded-lg flex items-center justify-center relative group`}>
              <div className="w-32 h-32 bg-yellow-400 rounded-lg flex items-center justify-center shadow-2xl group-hover:scale-110 transition-transform">
                <span className="text-6xl">📦</span>
              </div>
              <div className="absolute top-4 right-4 bg-black/20 text-white px-3 py-1 rounded-full text-sm">
                库存: {product.stock}
              </div>
              {product.probability && (
                <div className="absolute bottom-4 left-4 bg-orange-500 text-white px-3 py-1 rounded-full text-sm font-medium">
                  {product.probability}
                </div>
              )}
            </div>
            
            {/* 缩略图 */}
            <div className="grid grid-cols-4 gap-2">
              {Array.from({ length: 4 }, (_, i) => (
                <div key={i} className={`h-20 bg-gradient-to-br ${product.bgColor} rounded-lg flex items-center justify-center opacity-60 hover:opacity-100 transition-opacity cursor-pointer`}>
                  <span className="text-xl">📦</span>
                </div>
              ))}
            </div>
          </div>

          {/* 商品信息 */}
          <div className="space-y-6">
            <div>
              <div className="flex items-center space-x-2 mb-2">
                <span className="bg-gray-600 text-white px-2 py-1 rounded text-xs font-bold">
                  盲盒
                </span>
                <span className="bg-orange-100 text-orange-600 px-2 py-1 rounded text-xs font-medium">
                  热销
                </span>
              </div>
              <h1 className="text-3xl font-bold text-gray-800 mb-4">{product.name}</h1>
              <p className="text-gray-600 text-lg leading-relaxed">{product.description}</p>
            </div>

            {/* 价格信息 */}
            <div className="bg-white rounded-lg p-6 shadow-sm">
              <div className="flex items-baseline space-x-4 mb-4">
                <span className="text-4xl font-bold text-orange-600">¥{product.price}</span>
                <span className="text-lg text-gray-600">估值: {product.originalValue}</span>
              </div>
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="text-gray-600">当前库存:</span>
                  <span className="font-medium ml-2">{product.stock} 个</span>
                </div>
                <div>
                  <span className="text-gray-600">已售出:</span>
                  <span className="font-medium ml-2">{1000 - product.stock} 个</span>
                </div>
              </div>
            </div>

            {/* 购买选项 */}
            <div className="bg-white rounded-lg p-6 shadow-sm">
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  购买数量
                </label>
                <div className="flex items-center space-x-3">
                  <button
                    onClick={() => setQuantity(Math.max(1, quantity - 1))}
                    className="w-10 h-10 rounded-full border border-gray-300 flex items-center justify-center hover:bg-gray-50"
                  >
                    -
                  </button>
                  <span className="w-16 text-center text-lg font-medium">{quantity}</span>
                  <button
                    onClick={() => setQuantity(Math.min(10, quantity + 1))}
                    className="w-10 h-10 rounded-full border border-gray-300 flex items-center justify-center hover:bg-gray-50"
                  >
                    +
                  </button>
                  <span className="text-sm text-gray-500 ml-4">限购10个</span>
                </div>
              </div>

              <div className="flex space-x-4">
                <button
                  onClick={handleAddToCart}
                  disabled={isAdding}
                  className="flex-1 border border-orange-500 text-orange-600 font-bold py-3 px-6 rounded-lg hover:bg-orange-50 transition-colors disabled:opacity-50"
                >
                  {isAdding ? '添加中...' : '加入购物车'}
                </button>
                <button
                  onClick={handleBuyNow}
                  disabled={isAdding}
                  className="flex-1 bg-gradient-to-r from-yellow-400 to-orange-400 text-black font-bold py-3 px-6 rounded-lg hover:shadow-lg transition-shadow disabled:opacity-50"
                >
                  立即购买
                </button>
              </div>
            </div>

            {/* 商品特点 */}
            <div className="bg-white rounded-lg p-6 shadow-sm">
              <h3 className="font-semibold text-gray-800 mb-4">商品特点</h3>
              <div className="space-y-3">
                <div className="flex items-center space-x-3">
                  <span className="text-green-600">✓</span>
                  <span className="text-gray-700">7天无理由退货</span>
                </div>
                <div className="flex items-center space-x-3">
                  <span className="text-green-600">✓</span>
                  <span className="text-gray-700">正品保障</span>
                </div>
                <div className="flex items-center space-x-3">
                  <span className="text-green-600">✓</span>
                  <span className="text-gray-700">X光安全检测</span>
                </div>
                <div className="flex items-center space-x-3">
                  <span className="text-green-600">✓</span>
                  <span className="text-gray-700">环保循环理念</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* 详细说明 */}
        <div className="mt-12 bg-white rounded-lg p-8 shadow-sm">
          <h2 className="text-2xl font-bold text-gray-800 mb-6">商品详情</h2>
          <div className="prose max-w-none text-gray-600">
            <p className="mb-4">
              {product.name}是箱野精心挑选的神秘盲盒，每个盒子都经过严格的筛选和安全检测。
              我们从回收的滞留包裹中挑选出品质优良的商品，重新包装成充满惊喜的盲盒。
            </p>
            <p className="mb-4">
              这款盲盒可能包含各种{product.category === 'digital' ? '数码产品' : 
              product.category === 'lifestyle' ? '生活用品' : 
              product.category === 'fashion' ? '潮玩收藏品' : '高价值商品'}，
              让您在开箱的过程中体验到前所未有的惊喜与快乐。
            </p>
            <p>
              购买箱野盲盒，不仅能以超值的价格获得心仪商品，更是在为环保事业贡献一份力量。
              每一次开箱，都是对循环经济的支持，都是对地球环境的关爱。
            </p>
          </div>
        </div>

        {/* 相关推荐 */}
        {relatedProducts.length > 0 && (
          <div className="mt-12">
            <h2 className="text-2xl font-bold text-gray-800 mb-6">相关推荐</h2>
            <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-6">
              {relatedProducts.map((relatedProduct) => (
                <a
                  key={relatedProduct.id}
                  href={`/product/${relatedProduct.id}`}
                  className="bg-white rounded-lg shadow-sm hover:shadow-lg transition-shadow overflow-hidden group"
                >
                  <div className={`h-32 bg-gradient-to-br ${relatedProduct.bgColor} flex items-center justify-center`}>
                    <div className="w-16 h-16 bg-yellow-400 rounded-lg flex items-center justify-center shadow-xl group-hover:scale-110 transition-transform">
                      <span className="text-2xl">📦</span>
                    </div>
                  </div>
                  <div className="p-4">
                    <h3 className="font-semibold text-gray-800 mb-2">{relatedProduct.name}</h3>
                    <div className="text-lg font-bold text-orange-600">¥{relatedProduct.price}</div>
                  </div>
                </a>
              ))}
            </div>
          </div>
        )}
      </div>
      <ToastContainer />
    </div>
  );
}